package logic

import (
	"context"
	"crypto/rand"
	"encoding/base64"

	"greet/internal/svc"
	"greet/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type CipherGenerateLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewCipherGenerateLogic(ctx context.Context, svcCtx *svc.ServiceContext) *CipherGenerateLogic {
	return &CipherGenerateLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *CipherGenerateLogic) CipherGenerate(req *types.CipherGenerateRequest) (resp *types.CipherGenerateResponse, err error) {
	if req.Type == "SM4" {
		key := make([]byte, 16)
		if _, err := rand.Read(key); err != nil {
			panic(err)
		}
		iv := make([]byte, 16)
		if _, err := rand.Read(iv); err != nil {
			panic(err)
		}
		return &types.CipherGenerateResponse{
			Code: "success",
			Data: map[string]string{
				"key": base64.StdEncoding.EncodeToString(key),
				"iv":  base64.StdEncoding.EncodeToString(iv),
			},
		}, nil
	}

	return &types.CipherGenerateResponse{
		Code:    "error",
		Message: "加密失败",
	}, nil
}
